package com.example.administrator.officeplatform.Audit;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.administrator.officeplatform.MyApplication;
import com.example.administrator.officeplatform.R;
import com.example.administrator.officeplatform.adapter.SettlementAdatper;
import com.example.administrator.officeplatform.base.BaseActivity;
import com.example.administrator.officeplatform.bean.CostInfo;
import com.example.administrator.officeplatform.bean.ReimbursementVoInfo;
import com.example.administrator.officeplatform.bean.SettlementInfo;
import com.example.administrator.officeplatform.kj.AuditorActivity;
import com.example.administrator.officeplatform.kj.IpUtil;
import com.example.administrator.officeplatform.kj.NoScrollView;
import com.example.administrator.officeplatform.utils.JsonUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SettlementAuditActivity extends BaseActivity {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.rv_jsd)
    NoScrollView rv_jsd;
    @Bind(R.id.layout_btn1)
    LinearLayout layout_btn1;
    @Bind(R.id.layout_btn2)
    LinearLayout layout_btn2;
    @Bind(R.id.layout_btn3)
    LinearLayout layout_btn3;
    @Bind(R.id.layout_btn6)
    LinearLayout layout_btn6;
    @Bind(R.id.layout_btn7)
    LinearLayout layout_btn7;
    @Bind(R.id.layout_btn4)
    LinearLayout layout_btn4;
    @Bind(R.id.layout_fj)
    LinearLayout layout_fj;
    @Bind(R.id.layout_shr)
    LinearLayout layout_shr;
    private Context mContext;
    private List<AuditInfo> ls_audit;
    private Intent mIntent;
    private OkHttpClient mOkHttpClient= new OkHttpClient();
    private ProgressDialog mProgressDialog;
    private List<CostInfo> ls_cost;
    private ReimbursementVoInfo reimbursementVoInfo = new ReimbursementVoInfo();
    private List<SettlementInfo> settlementInfos;
    private SettlementInfo settlementInfo;
    private ReimbursementVoInfo newInfo;
    private String id = "";
    private String nextAuditorId ="";
    private TextView tv_enclosureNum,tv_shr;
    private String who = "0";
    private EditText ed_remarks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_settlement_audit);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        mContext=this;
        //设置布局管理器
        rv_jsd.setLayoutManager(new LinearLayoutManager(mContext));
        rv_jsd.setHasFixedSize(true);
        rv_jsd.setItemAnimator(new DefaultItemAnimator());
        tv_enclosureNum = (TextView)findViewById(R.id.tv_enclosureNum);

    }

    @Override
    protected void initData() {
        mIntent = getIntent();

        ls_audit= new ArrayList<>();
        settlementInfos = new ArrayList<>();
        String type = (String) mIntent.getExtras().get(
                "type");
        who = (String) mIntent.getExtras().get(
                "who");

        if ("1".equals(type)){
            reimbursementVoInfo = (ReimbursementVoInfo) mIntent.getExtras().get(
                    "ReimbursementVoInfo");
            settlementInfos = reimbursementVoInfo.getSettlementInfoVoList();
            id = reimbursementVoInfo.getId();
            getdata();
            tv_enclosureNum.setText(reimbursementVoInfo.getEnclosureNum());
            tv_enclosureNum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!isNull(tv_enclosureNum)) {
                        if (!reimbursementVoInfo.getEnclosureNum().equals(0)) {
                            Intent intent = new Intent();
                            intent.setClass(getApplicationContext(), ShowImageActivity.class);
                            Bundle bundle = new Bundle();
                            intent.putExtra("who", who);
                            intent.putExtra("ProcessState", String.valueOf( reimbursementVoInfo.getProcessState()));
                            bundle.putSerializable("ReimbursementVoInfo", newInfo);
                            intent.putExtras(bundle);
                            startActivityForResult(intent, 1);
                        }
                    }
                }
            });


            id = reimbursementVoInfo.getId();

            if (who.equals("1")){
                /**判断是否可以提交*/

                String processState =String.valueOf(reimbursementVoInfo.getProcessState());
                if (processState.equals("1")){
                    showBtn3();
                }

            }else if (who.equals("0")){
                /**判断是否可以审核驳回*/
                Boolean end = reimbursementVoInfo.isEnd();
                int myState  = reimbursementVoInfo.getMyState();
                int nodeType  = reimbursementVoInfo.getNodeType();
                if (end==false){
                    if(myState==1) {
                        if (nodeType == 1) {
                            showBtn2();
                        } else if (nodeType == 2) {
                            showButton1();
                        }

                    }else if(myState==3){}

                }else if (end==true){
                    if(myState==1){
                        if (nodeType == 1) {
                            showBtn7();
                        } else if (nodeType == 2) {
                            showButton6();
                        }
                    }
                }}

        }else if ("0".equals(type)){
            settlementInfo = (SettlementInfo) mIntent.getExtras().get(
                    "settlementInfo");
            settlementInfos = settlementInfo.getSettlementVos();
            layout_btn1.setVisibility(View.GONE);
            if(settlementInfos!=null){
                if(settlementInfos.size()>0){
                    setdata();
                    layout_fj.setVisibility(View.GONE);
                }
            }
        }






    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }

    private void showButton1(){
        layout_btn1.setVisibility(View.VISIBLE);
        layout_shr.setVisibility(View.VISIBLE);
        tv_shr.setVisibility(View.VISIBLE);
        tv_shr = (TextView)findViewById(R.id.tv_shr);
        tv_shr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent();
                intent2.setClass(mContext, AuditorActivity.class);
                intent2.putExtra("index",id);
                startActivityForResult(intent2, 1);            }
        });
        Button btn_sure = (Button)findViewById(R.id.btn_sure);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isNull(tv_shr)){
                    Toast.makeText(mContext, "请选择下一审核人！", Toast.LENGTH_SHORT).show();
                    return;
                }
                suredata();
            }
        });
    }
    private void showButton6(){
        layout_btn6.setVisibility(View.VISIBLE);
        nextAuditorId = "";
        Button btn_sure = (Button)findViewById(R.id.btn_sp);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                suredata();
            }
        });
    }


    private void setdata(){


        SettlementAdatper settlementAdatper = new SettlementAdatper(settlementInfos,mContext);
        rv_jsd.setAdapter(settlementAdatper);

        settlementAdatper.setOnRecyclerViewListener(new SettlementAdatper.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                if (settlementInfos.get(position).getSettlementVos()==null || settlementInfos.get(position).getSettlementVos().size()==0){

                }else {
                    SettlementInfo info = reimbursementVoInfo.getSettlementInfoVoList().get(position);
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), SettlementAuditActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("settlementInfo",info);
                    intent.putExtra("type","0");
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                }
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });

    }


    /**
     *审核的数据请求
     *@author Wangzhiqiang
     *Created on 2017/12/23 16:09
     */

    private void suredata(){
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mOkHttpClient = new OkHttpClient();

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("nextAuditorId", nextAuditorId);
        String json1 = JSON.toJSONString(map);
        RequestBody formBody =  FormBody.create(MediaType.parse("application/json;charset=UTF-8"),json1);
        String s = MyApplication.getMsession();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement/examine")
                .header("cookie", MyApplication.getMsession())
                .addHeader("Content-Type","application/json;charset=UTF-8")
                .post(formBody)
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                if(str.indexOf("success")>=0) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "操作成功", Toast.LENGTH_SHORT).show();
                            Intent mIntent = new Intent();
                            setResult(1, mIntent);
                            finish();
                        }
                    });
                }
            }

        });


    }


    /**
     *获取数据
     *@author Wangzhiqiang
     *Created on 2017/12/21 18:58
     */
    private void getdata(){
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mOkHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement/getReimbursementById/"+id)
                .header("cookie", MyApplication.getMsession())
                .build();

        Call call = mOkHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();
                String str = response.body().string();
                if(str.indexOf("reimbursementCode")>=0) {
                    newInfo = JsonUtil.getPerson(str, ReimbursementVoInfo.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            settlementInfos = newInfo.getSettlementInfoVoList();
                            setdata();
                        }
                    });

                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "查询报销单信息出现错误", Toast.LENGTH_SHORT).show();

                        }
                    });
                }
            }
        });

    }
    /**
     *显示两个按钮
     *@author Wangzhiqiang
     *Created on 2017/12/22 19:00
     */
    private void showBtn2(){
        layout_btn2.setVisibility(View.VISIBLE);
        layout_shr.setVisibility(View.VISIBLE);
        tv_shr = (TextView)findViewById(R.id.tv_shr);
        ed_remarks = (EditText) findViewById(R.id.ed_remarks);
        tv_shr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent();
                intent2.setClass(mContext, AuditorActivity.class);
                intent2.putExtra("index",id);
                startActivityForResult(intent2, 1);            }
        });
        Button btn_sh = (Button)findViewById(R.id.btn_sh);
        btn_sh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isNull(tv_shr)){
                    Toast.makeText(mContext, "请选择下一审核人！", Toast.LENGTH_SHORT).show();
                    return;
                }
                suredata();
            }
        });

        Button btn_bh = (Button)findViewById(R.id.btn_sc);
        btn_bh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isNull(ed_remarks)){
                    Toast.makeText(mContext, "请填写备注！", Toast.LENGTH_SHORT).show();
                    return;
                }
                rejectData();
            }
        });
    }

    /**
     *显示一个按钮
     *@author Wangzhiqiang
     *Created on 2017/12/22 18:58
     */

    private void showBtn3(){
        layout_btn3.setVisibility(View.VISIBLE);
        layout_shr.setVisibility(View.VISIBLE);
        tv_shr = (TextView)findViewById(R.id.tv_shr);
        tv_shr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent();
                intent2.setClass(mContext, AuditorActivity.class);
                intent2.putExtra("index",id);
                startActivityForResult(intent2, 1);            }
        });
        Button btn_sure = (Button)findViewById(R.id.btn_tj);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isNull(tv_shr)){
                    Toast.makeText(mContext, "请选择审核人", Toast.LENGTH_SHORT).show();
                    return;
                }
                sendExpense();
            }
        });
    }

    /**
     *显示两个按钮
     *@author Wangzhiqiang
     *Created on 2017/12/22 19:00
     */
    private void showBtn7(){
        layout_btn7.setVisibility(View.VISIBLE);
        ed_remarks = (EditText) findViewById(R.id.ed_remark);
        nextAuditorId = "";
        Button btn_sh = (Button)findViewById(R.id.btn_sp7);
        btn_sh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                suredata();
            }
        });

        Button btn_bh = (Button)findViewById(R.id.btn_bx7);
        btn_bh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = ed_remarks.getText().toString();
                if (isNull(ed_remarks)){
                    Toast.makeText(mContext, "请填写备注！", Toast.LENGTH_SHORT).show();
                    return;
                }
                rejectData();
            }
        });
    }
    /**
     *显示一个按钮
     *@author Wangzhiqiang
     *Created on 2017/12/22 18:58
     */

    private void showBtn4(){

        layout_btn4.setVisibility(View.VISIBLE);
        Button btn_sure = (Button)findViewById(R.id.btn_xg);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "正在开发...", Toast.LENGTH_SHORT).show();
                return;

            }
        });
    }
    /**
     *申请报销单数据请求
     *@author Wangzhiqiang
     *Created on 2017/12/21 10:21
     */
    private void sendExpense(){

        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);

        mOkHttpClient = new OkHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("nextAuditorId", nextAuditorId);
        String json1 = JSON.toJSONString(map);
        RequestBody formBody =  FormBody.create(MediaType.parse("application/json;charset=UTF-8"),json1);
        String s = MyApplication.getMsession();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement/submitReimbursement")
                .header("cookie", MyApplication.getMsession())
                .addHeader("Content-Type","application/json;charset=UTF-8")
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接服务器异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();

                String str = response.body().string();
                //{"messageType":2,"type":"success","title":"操作信息","message":"提交成功","data":null}
                if(str.indexOf("success")>=0){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
                            finish();

                        }
                    });
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        });
    }

    /**
     *驳回的数据请求
     *@author Wangzhiqiang
     *Created on 2017/12/23 16:17
     */

    private void rejectData(){
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);

        mOkHttpClient = new OkHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("remarks", ed_remarks.getText().toString());
        String json1 = JSON.toJSONString(map);
        RequestBody formBody =  FormBody.create(MediaType.parse("application/json;charset=UTF-8"),json1);
        String s = MyApplication.getMsession();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement/reject")
                .header("cookie", MyApplication.getMsession())
                .addHeader("Content-Type","application/json;charset=UTF-8")
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                if(str.indexOf("success")>=0) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "操作成功", Toast.LENGTH_SHORT).show();
                            Intent mIntent = new Intent();
                            setResult(1, mIntent);
                            finish();
                        }
                    });
                }
            }

        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == 8){
            String name = data.getExtras().getString("name");
            nextAuditorId = data.getExtras().getString("id");
            tv_shr.setText(name);
        }
        if (resultCode == 1){
            newInfo = (ReimbursementVoInfo)data.getExtras().get("ReimbursementVoInfo");
        }
    }
}
